package nio.groupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
public class Server {
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 8888;

    public Server() {
        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //监听方法
    public void listen() {

        try {
            while (true) {
                int count = selector.select(2000);

                if (count > 0) {

                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

                    while (iterator.hasNext()) {

                        SelectionKey key = iterator.next();

                        if (key.isAcceptable()) {

                            SocketChannel socketChannel = listenChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);

                            System.out.println(socketChannel.getRemoteAddress() + "上线");
                        }
                        if (key.isReadable()) {
                            //处理读事件
                            readData(key);

                        }

                        //iterator.remove();
                    }
                } else {
                    //System.out.println("等待中....");
                }


            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //读取客户端消息
    public void readData(SelectionKey key){
        SocketChannel channel = null;
        try {

            channel =(SocketChannel) key.channel();
            ByteBuffer buf = ByteBuffer.allocate(1024);
            int count = channel.read(buf);
            String msg = new String(buf.array());
            if (count>0){
                System.out.println("客户端: "+msg);
                //向其他客户端转发消息
                sendInfoToOtherClient(msg,channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + "离线了");
                key.channel();
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    //向其他客户端发送信息
    public void sendInfoToOtherClient(String msg,SocketChannel self){
        try {
            System.out.println("服务器转发消息中...");
            for (SelectionKey key : selector.keys()) {
                Channel channel = key.channel();

                if (channel instanceof SocketChannel && channel != self){
                    SocketChannel dst = (SocketChannel) channel;

                    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());

                    dst.write(buffer);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

    }

    public static void main(String[] args) {
        Server server = new Server();
        server.listen();
    }
}
